package com.shqcjd.siemensglass.http;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * 声网访问api需要认证
 * Created by sy on 2018/7/10.
 */

public class AuthOkHttpUtils {
    private final static long HTTP_CONNECT_TIMEOUT = 10;
    private final static long HTTP_READ_TIMEOUT = 30;
    private static OkHttpClient singleton;
    public static OkHttpClient getInstance(final String name, final String pwd) {
        if (singleton == null) {
            synchronized (OkHttpClient.class) {
                if (singleton == null) {
                    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLogger());
                    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    OkHttpClient.Builder builder = new OkHttpClient.Builder();
                    builder.connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS)
                            .authenticator(new Authenticator() {
                                @Override
                                public Request authenticate(Route route, okhttp3.Response response) throws IOException {
                                    String credential = Credentials.basic(name, pwd);
                                    return response.request().newBuilder().header("Authorization", credential).build();
                                }
                            })
                            .addInterceptor(interceptor);
                    singleton = builder.build();

                }
            }
        }
        return singleton;
    }
}
